package com.qf.util;

import com.qf.bean.Employee;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.获得session对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();//获取请求路径
        System.out.println("uri=" + requestURI);
        if (requestURI.endsWith("login.jsp") || requestURI.endsWith("login") || requestURI.endsWith(".css") || requestURI.contains("/img") || requestURI.equals("/")) {  //放行
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            Employee emp = (Employee) request.getSession().getAttribute("user");
            if (emp == null) {
                response.setContentType("text/html;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.print("<script>alert('请先登录');location.href='login.jsp'</script>");
            } else {
                //放行
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {

    }
}